package helperx

import (
	"encoding/base64"
	"encoding/hex"
	"errors"

	"github.com/spotlight21c/aesencryptor"
)

// AesEcbEncrypt AES ECB加密
// key为base64后的密钥字符串
// keyRaw 表示密钥是否为hex后的
// encryptRaw 为 false 则会输出hex
func AesEcbEncrypt(plain, key string, keyRaw, encryptRaw bool) (string, error) {
	if plain == "" {
		return "", errors.New("empty data")
	}

	keyStr := key
	if !keyRaw {
		// 解码密钥
		k, err := base64.StdEncoding.DecodeString(key)
		if err != nil {
			return "", err
		}
		keyStr = string(k)
	}

	if !validKey(keyStr) {
		return "", errors.New("invalid key size")
	}

	// 加密
	encValue, err := aesencryptor.Encrypt(plain, keyStr)
	if err != nil {
		return "", err
	}

	// 如果不需要原始密文，则返回hex后的密文
	if !encryptRaw {
		return hex.EncodeToString(encValue), nil
	}
	return string(encValue), nil
}

// AesEcbDecrypt AES ECB解密
// key为base64后的密钥字符串
// keyRaw 表示密钥是否为hex后的
// secretRaw 为 false 则会将secret 进行hex decode
func AesEcbDecrypt(secret, key string, keyRaw, secretRaw bool) (string, error) {
	if secret == "" {
		return "", errors.New("secret is empty")
	}

	keyStr := key
	if !keyRaw {
		// 解码密钥
		k, err := base64.StdEncoding.DecodeString(key)
		if err != nil {
			return "", err
		}
		keyStr = string(k)
	}

	if !validKey(keyStr) {
		return "", errors.New("invalid key size")
	}

	// 如果密文是hex的，则将其hex decode
	var cryptByte []byte
	if !secretRaw {
		decodeHex, err := hex.DecodeString(secret)
		if err != nil {
			return "", err
		}
		cryptByte = decodeHex
	} else {
		cryptByte = []byte(secret)
	}

	// 解密
	plain, err := aesencryptor.Decrypt(cryptByte, []byte(keyStr))
	if err != nil {
		return "", err
	}

	return string(plain), nil
}
